import { defineStore } from 'pinia'
import { get, post } from '@/utils'
import { setToken, clear, setExTime } from '@/utils/auth'
import { removeRouteListener } from '@/utils/route-listener'
import { UserState } from './types'
import useAppStore from '../app'
import md5 from 'md5'
import cloneDeep from 'lodash/cloneDeep'

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    name: undefined,
    avatar: undefined,
    job: undefined,
    organization: undefined,
    location: undefined,
    email: undefined,
    introduction: undefined,
    personalWebsite: undefined,
    jobName: undefined,
    organizationName: undefined,
    locationName: undefined,
    phone: undefined,
    registrationDate: undefined,
    accountId: undefined,
    certification: undefined,
    role: '',
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state }
    },
  },

  actions: {
    switchRoles() {
      return new Promise(resolve => {
        this.role = this.role === 'user' ? 'admin' : 'user'
        resolve(this.role)
      })
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial)
    },

    // Reset user's information
    resetInfo() {
      this.$reset()
    },

    // Get user's information
    async info() {
      // const res = await getUserInfo();
      // this.setInfo(res.data);
    },

    // Login
    async login(loginForm, cb?: Function) {
      const query = cloneDeep(loginForm)
      if (query.password) query.password = md5(query.password)
      get(
        {
          url: '/server-auth/oauth/token',
          data: query,
          headers: {
            'Captcha-Key': loginForm.CaptchaKey,
            'Captcha-Code': loginForm.CaptchaCode,
          },
        },
        async ({ data }) => {
          setToken(data.access_token)
          sessionStorage.setItem('name', data.nick_name)
          sessionStorage.setItem('refresh_token', data.refresh_token)
          setExTime()
          cb?.(true)
        },
        () => {
          // clear();
          cb?.(false)
        }
      )
    },
    refeshToken() {
      console.log('refeshtoken')
      return new Promise((resolve, reject) => {
        const query = {
          refresh_token: sessionStorage.getItem('refresh_token'),
          grant_type: 'refresh_token',
        }
        console.log(query)
        this.login(query, () => {
          resolve(true)
        })
      })
    },
    logoutCallBack() {
      const appStore = useAppStore()
      this.resetInfo()
      clear()
      removeRouteListener()
      appStore.clearServerMenu()
      location.reload()
    },
    // Logout
    async logout() {
      try {
      } finally {
        this.logoutCallBack()
      }
    },
  },
})

export default useUserStore
